import React, { useMemo, useState, useEffect } from 'react';
import { Title } from 'base/ctl/title';
import { useStep } from 'use/step';
import { get_path } from 'base/ctl/base';
import { MainMenu } from 'base/ctl/menu';
import { Time } from 'base/ctl/base';
import { DlgLog } from 'base/ctl/log';
import { IkFind, useForm, Btn, filter_row, is_empty, PanelFind, GridTable, no_del, uDb, cline, obj_int, uJob, PanelBt, obj_str, uPrint,
    d_sort, obj_float, obj_str_trim, Wait, NuiBt, useHigh } from 'sui';
import { loc } from 'local/index';
import { get_tp, get_tp_mod, reload, load_stuff, load_supply, load_ng } from './cmd';
import { DlgVal, DlgNg } from './ctl';
import { DlgPrint } from '../stock/in/ctl';
import { up_qr } from '../stock/cmd';

const ClientView = ({ umd, wsn }) => {
    const [open_print, openPrint] = useState(false);
    const [filter, setFilter] = useState();
    const [cur, setCur] = useState();
    const [open_ok, openOk] = useState(false);
    const [open_ng, openNg] = useState(false);
    const [cur_out, curOut] = useState();
    const [supply, setSupply] = useState();
    const [stuff, setStuff] = useState();
    const [open_menu, openMenu] = useState(false);
    const [open_log, openLog] = useState(false);
    const [wait, setWait] = useState(false);
    const [lst_tech, lstTech] = useState();
    const [lst_ball, lstBall] = useState();
    const [ng, setNg] = useState();
    const [main, setMain] = useState();
    const [high] = useHigh(260, 200)
    const [value, setValue] = useState();
    const form = useForm(setValue);

    useEffect(() => {
        load_supply(setSupply);
        load_stuff(setStuff);
        load_ng(setNg);
    }, []);

    const hok = (v) => {
        setWait(true);

        let num = obj_int(v, "num");
        const box = obj_int(v, "box");
        const snum = obj_int(v, "snum");

        const cmd = {
            line: cline(),
            sn: obj_str(cur, "sn"),
            qa: obj_str(v, "level"),
            tp: get_tp_mod(cur_out),
            num: num,
            snum: snum,
            box: box,
        };

        uJob(null, "stock/qa", cmd,
            pcmd => {
                reload(() => setWait(false), cur_out, setMain);

                pcmd["tmpl"] = cur_out.toLowerCase();
                up_qr(pcmd, snum);

                num -= snum;

                uPrint(null, pcmd);

                for (let i = 1; i < box; i++) {
                    if (num < snum) {
                        up_qr(pcmd, num);
                        uPrint(null, pcmd);

                        break;
                    } else {
                        up_qr(pcmd, snum);
                        uPrint(null, pcmd, null, null, false);
                    }

                    num -= snum;
                }
            },
            e => {
                alert("修改失败");
                setWait(false);
            });
    };

    const hng = (v) => {
        setWait(true);

        let num = obj_int(v, "num");

        const cmd = {
            line: cline(),
            sn: obj_str(cur, "sn"),
            ngson: obj_str(v, "ngson"),
            tp: get_tp_mod(cur_out),
            num: num,
        };

        uJob(null, "stock/defeat", cmd,
            pcmd => reload(() => setWait(false), cur_out, setMain),
            e => {
                alert("修改失败");
                setWait(false);
            });
    };

    const hclose = (v) => {
        if (no_del("确认关结")) {
            return;
        }

        const mod = get_tp(cur_out);
        if (!mod) {
            return;
        }

        setWait(true);

        uDb(null, `file/md/${mod}`,
            {
                line: cline(),
                sn: obj_str(v, "sn"),
                v: {
                    state: "close"
                }
            },
            r => reload(() => setWait(false), cur_out, setMain),
            e => setMain(null));
    };

    useEffect(() => {
        if (is_empty(main)) {
            return;
        }

        const set_tech = new Set();
        const set_ball = new Set();

        const ret_tech = [];
        const ret_ball = [];

        main.forEach(d => {
            const tech = obj_str_trim(d, "tech");
            if (!set_tech.has(tech)) {
                ret_tech.push({ id: tech, sn: tech, name: tech });
                set_tech.add(tech);
            }

            const ball = obj_float(d, "ball");
            if (!set_ball.has(ball)) {
                ret_ball.push({ id: "" + ball, sn: ball, name: ball });
                set_ball.add(ball);
            }
        });

        d_sort(ret_tech, "sn");
        d_sort(ret_ball, "sn");

        lstTech(ret_tech);
        lstBall(ret_ball);
    }, [main]);

    const getRow = useMemo(() => {
        if (is_empty(main)) {
            return null;
        }

        const opt_tech = obj_str_trim(value, "tech");
        const opt_ball = obj_str_trim(value, "ball");
        const opt_st = obj_str_trim(value, "state");

        const tmp = main.filter(d => {
            if (opt_tech) {
                if (obj_str_trim(d, "tech") !== opt_tech) {
                    return false;
                }
            }

            if (opt_ball) {
                if (obj_str_trim(d, "ball") !== opt_ball) {
                    return false;
                }
            }

            if (opt_st) {
                if (obj_str_trim(d, "state") !== opt_st) {
                    return false;
                }
            }

            return true;
        });

        const lst = ["sn", "ball", "tech"];

        return filter_row(tmp, lst, filter);
    }, [main, filter, value]);

    const lst_st = [
        {id: "open", sn: "open", name: "开立"},
        {id: "run", sn: "run", name: "运行"},
    ];

    const getCol = useMemo(() => {
        if (!cur_out) {
            return null;
        }

        const col = [
            {name: "物料批次号", key: 'sn', width: 200},
            {name: "材料", key: 'stuff', width: 100, formatter: (props) => {
                const d = props.row;

                const k = obj_str(d, "stuff");
                const f = obj_str(stuff, k);
                if (f) {
                    return f;
                }

                return k;
            }},
            {name: "供应商", key: 'supply', width: 200, formatter: (props) => {
                const d = props.row;

                const k = obj_str(d, "supply");
                const f = obj_str(supply, k);
                if (f) {
                    return f;
                }

                return k;
            }},
            {name: "球径", key: 'ball', width: 100},
            {name: "型号", key: 'tech', width: 100},
            {name: "数量", key: 'num', width: 100},
        ];

        if (cur_out === "C") {
            col.push({name: "材料牌号", key: 'stuffnum', width: 200});
            col.push({name: "来料日期", key: 'gtime', width: 200});
            col.push({name: "机床编号", key: 'machine', width: 200});
        }

        if (cur_out === "S") {
            col.push({name: "AB面", key: 'face', width: 100});
            col.push({name: "送货批次", key: 'NB', width: 200});
        }

        const hAction = (d, v) => {
            setCur(d);
            if (v === "ok") {
                openOk(true);
            } else if (v === "ng") {
                openNg(true);
            }
        };

        col.push({name: "状态", key: 'state', width: 80, formatter: (props) => {
            const d = props.row;

            const k = obj_str(d, "state");
            const f = lst_st.find(t => t.sn === k);
            if (f) {
                return f.name;
            }

            return k;
        }});

        col.push({name: loc("client_23"), key: 'e_opt', width: 240, formatter: (props) => {
            const d = props.row;

            return (
                <div className="inline-flex">
                    <Btn hcmd={() => hAction(d, "ok")}>检验合格</Btn>
                    <Btn className="mx-2" hcmd={() => hAction(d, "ng")}>不合格</Btn>
                    <Btn hcmd={() => hclose(d)}>关结</Btn>
            </div>
            );
        }});

        return col;
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [cur_out, stuff, supply]);

    const hSelect = (val) => {
        curOut(val);

        setWait(true)

        reload(() => setWait(false), val, setMain);
    };

    const menu = [{
        label: "补打标签",
        name: "rprint",
        hcmd: () => openPrint(true),
    }, {
        label: loc("base_157"),
        name: "log",
        hcmd: () => openLog(true),
    }];

    const Left = () => {
        if (!cur_out) {
            return null;
        }

        const hsyn = () => {
            setWait(true)

            reload(() => {
                setWait(false);
                alert("同步完成");
            }, cur_out, setMain);
        };

        return (
            <div className="inline-flex items-center">
                <NuiBt hcmd={hsyn} color="teal" className="mr-8">同步数据</NuiBt>
                <IkFind className="mr-4" label="型号" name="tech" mg="dense" lst={lst_tech} value={value} form={form}/>
                <IkFind className="mr-4" label="球径" name="ball" mg="dense" lst={lst_ball} value={value} form={form}/>
                <IkFind className="mr-4" label="状态" name="state" mg="dense" lst={lst_st} value={value} form={form}/>
                <NuiBt hcmd={() => setValue({})} className="mr-8">清空选项</NuiBt>
            </div>
        );
    };

    const getView = () => {
        if (!cur_out) {
            return null;
        }

        return (
            <div className="flex flex-col w-full">
                <PanelFind left={<Left/>} hcmd={setFilter}/>
                <GridTable col={getCol} row={getRow} high={high} rowHeight={45}/>
            </div>
        );
    };

    return (
        <div className="flex flex-col ml-2 mr-1">
            <div className="inline-flex mt-2 justify-between">
                <div className="inline-flex items-center">
                    <div className="ml-2 mr-4">
                        <MainMenu value={menu} open={open_menu} setOpen={openMenu}/>
                    </div>
                    <Title label="物料检测" width="w-56"/>
                </div>
                <Time className="text-2xl"/>
            </div>
            <div className="inline-flex ml-2 mt-4">
                <PanelBt name="C" select={cur_out === "C"} hcmd={() => hSelect("C")} className="mr-4" cl="indigo">保持架</PanelBt>
                <PanelBt name="S" select={cur_out === "S"} hcmd={() => hSelect("S")} cl="indigo">密封圈</PanelBt>
            </div>
            <div className="flex flex-row items-start mt-1">
                {getView()}
            </div>
            <DlgLog open={open_log} setOpen={openLog}/>
            <DlgVal open={open_ok} setOpen={openOk} cur={cur} hcmd={hok}/>
            <DlgNg open={open_ng} setOpen={openNg} cur={cur} hcmd={hng} mod={cur_out} ng={ng}/>
            <Wait wait={wait}/>
            <DlgPrint open={open_print} setOpen={openPrint} mt="order"/>
        </div>
    );
};

const QaClient = ({ pathname, mod }) => {
    const [line, wsn] = get_path(pathname, mod);
    const umd = useStep(line, wsn);

    return <ClientView umd={umd} wsn={wsn}/>;
};

export {QaClient};
